package com.lzcu.maoyan.mapreduce.mapreduce.reduce;

import com.lzcu.maoyan.mapreduce.service.impl.PhoenixMapperImpl;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Reducer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author WangLiang
 * @date `2024/3/25`
 */
public class MovieReduce extends Reducer<Text, Text, Text, Text> {
    private static final Logger logger = LoggerFactory.getLogger(MovieReduce.class);

    @Override
    protected void reduce(Text key, Iterable<Text> values, Context context) throws IOException, InterruptedException {
        String result = "";
        for (Text value : values) {
            result = value.toString();
        }
        Map<String, Object> movieInfo = new HashMap<>();
        String[] keyInfo = key.toString().split("\001");
        movieInfo.put("movieName", keyInfo[0]);
        movieInfo.put("movieTime", keyInfo[1]);
        String[] valueInfo = result.split("\001");
        movieInfo.put("ticketProportion", valueInfo[0]);
        movieInfo.put("movieFrequency", valueInfo[1]);
        movieInfo.put("frequencyProportion", valueInfo[2]);
        movieInfo.put("moviePeople", valueInfo[3]);
        movieInfo.put("peopleProportion", valueInfo[4]);
        movieInfo.put("upDay", valueInfo[5]);
        movieInfo.put("totalSessions", valueInfo[6]);
        try {
            new PhoenixMapperImpl().insertMovie(movieInfo);
            context.write(key, new Text(result));
        } catch (Exception e) {
            logger.error(movieInfo.toString());
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }
}